package net.pm.core.service.pmuser.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import net.pm.common.dao.GenericDao;
import net.pm.common.service.impl.GenericServicerImpl;
import net.pm.common.toolkit.PMTool;
import net.pm.core.entities.db.Loginlog;
import net.pm.core.service.pmuser.LoginLogServicer;

import org.springframework.stereotype.Service;

@Service("LoginLogServicer")
public class LoginLogServicerImpl extends GenericServicerImpl<Loginlog, String> implements LoginLogServicer {

	@Resource(name="LoginLogDao")
	@Override
	public void setGenericDao(GenericDao<Loginlog, String> genericDao) {
		super.genericDao = genericDao;
	}

	@Override
	public List<Loginlog> findLoginlogs(Date startdate, Date enddate,
			Integer deptId, Long userId, Short logResultKey) {
		final StringBuilder builder = new StringBuilder(
				"from Loginlog log where 1=1 ");
		List<Object> args = new ArrayList<Object>();
		
		if (PMTool.isNotEmpty(userId)) {
			builder.append(" and log.pmuser.id = ? ");
			args.add(userId);
		} else {
			builder.append(" and log.pmuser.pmdept.id = ? ");
			args.add(deptId);
		}

		if (PMTool.isNotEmpty(startdate)) {
			builder.append(" and log.loginTime >= ? ");
			args.add(startdate);
		}
		if (PMTool.isNotEmpty(enddate)) {
			builder.append(" and log.loginTime <= ? ");
			args.add(enddate);
		}
		
		// 登录状态
		Short[] logResults = obtainLogResults(logResultKey);
		if(PMTool.isEmpty(logResults)){
			builder.append(" and log.logResult  = ? ");
			args.add(logResultKey);
		}else{
			builder.append(" and log.logResult in (-1 ");
			for (Short s : logResults) {
				builder.append(",").append(" ? ");
				args.add(s);
			}
			builder.append(" ) ");
		}
	
		
		builder.append(" order by log.loginTime desc ");
		return super.findEntitiesByJpql(builder, args.toArray());

	}

	private Short[] obtainLogResults(Short logResultKey){
		return LoginLogServicer.logResultMap.get(logResultKey);
	}

}
